<?php

Yii::import('application.extensions.tcpdf.tcpdf.*');
require_once('config/lang/eng.php');
require_once('tcpdf.php');

function convertDateToUS($date){

    $date = explode('-',$date);
    if(isset($date['1']))
        return $date[1].'/'.$date[2].'/'.$date[0];
}

class PdfController extends Controller
{

    public function actionContract($contractid, $mail = false, $invoicepdf = null, $salesorderpdf = null, $quotepdf = null){
        ContractPdfUtil::makeContractPdf($contractid, $mail , $invoicepdf, $salesorderpdf , $quotepdf);
    }

    public function actionEarnedReportByState(){
        $model = new EarnedReportByStateForm();
        if(isset($_POST['EarnedReportByStateForm'])){
            $model->attributes = $_POST['EarnedReportByStateForm'];
            if(isset($_POST['getCsv'])){
                $model->getCsv();
                Yii::app()->end();
            }else if(isset($_POST['getHtml'])){
                $data = $model->prepareDataForHtml();
                $this->layout = '//layouts/space';
                $this->render('earnedReportByState',array(
                    'data'=>$data,
                    'model'=>$model
                ));
                Yii::app()->end();
            }

        }
        $this->render(
            'earnedReportByStateForm',
            array(
                'model'=>$model
            )
        );
    }
    public function actionContractReport($custno, $type, $beta = false,$mail = false, $paid = false, $startdate=false, $enddate=false)
    {
        $customer = Customers::model()->findByPk($custno);
        $pdf = new CRPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'ANSI_A', true, 'UTF-8', false);
        $pdf->setCustomer($customer);
        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('Statement Report');
        $pdf->SetSubject('Statement Report');
        $pdf->SetKeywords('');
        $pdf->setPrintHeader(true);
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        $pdf->SetFont('dejavusans', '', 10);
        $pdf->AddPage();
        //payments section
        $reportName = $customer->custno . '-Contract-report-' . date('Y-m-d') . '.pdf';
        $html = '<H4 align="center">Contract Type : ' . ContractType::getText($type) . '</H4><br/><br/>';
        $pdf->writeHTML($html, true, false, true, false, '');
        $criteria = new CDbCriteria();
        $criteria->condition = "custno=$custno and contractype=$type";
        if ($startdate)
            $criteria->addColumnCondition(array('contractstartdate' => $startdate));
        if ($enddate)
            $criteria->addColumnCondition(array('contractenddate' => $enddate));
        $conractList = Contracts::model()->findAll($criteria);

        $contractTable = '';
        $contractTotal = 0;
        $totalPq = 0;
        $billed = 0;
        $totalPayment = 0;
        foreach ($conractList as $contract)
        {
            /** @var $contract Contracts */
            /** @var $location Locations */
            $location = $contract->getLocation();
            $contractTable .= '
                <table >
                    <tr>
                        <td colspan="5" style="border-top: 2px double black;border-bottom: 2px double black;">
                            <b>Contract No: ' . $contract->contractid;
            $pq = ($contract->pre_quote_amount);
            $totalPq+=$pq;
            if($beta == 1)
            {

                $contractTable.=' PQ: '.$pq;
            }
            $contractTable.='</b>
                        </td>
                    </tr>';
            if ($contract->billtype != Contracts::TYPE_YEARLY && $paid)
            {
                $contractTable .= ' <tr>
        <td colspan="5" >
             <b>Amount: ' . $contract->pre_quote_amount . '</b>
        </td>
        </tr> ';
            }
            $contractTable .='
        <tr>
        <td width="150px"></td>
        <td align="left" width="230px">
           ' . $location->locname . '<br/>
        &nbsp;  ' . $location->add1 . ' <br/>
        &nbsp;  ' . "$location->city, $location->state $location->zip" . ' <br/>
        </td>
        <td align="right" width="130px" style="font-weight:bold">
           Billing      <br/>
                Start:  <br/>
                End:         <br/>

        </td>
        <td align="right"  width="150px">
            ' . $contract->getBillTypeText() . ' <br/>
            ' . $contract->contractstartdate . '<br/>
            ' . $contract->contractenddate . '<br/>
        </td>
        <td></td>
        </tr>';
            $invSum = 0;
            /*                 * @var $invoice Invoice */
            foreach ($contract->invoiceAndCMList as $invoice)
            {
                $invoiceAmountWithDiscount = $invoice->getAmountWithDiscount();
                if($invoice->invoicetype == 'Invoice'){
                    $billed += $invoiceAmountWithDiscount;
                }else if($invoice->invoicetype == 'Credit Memo' ){
                    $billed += $invoiceAmountWithDiscount;
                }

                $payment = $invoice->getPaymentApplied();
                $totalPayment += $payment;
                if ($paid)
                    $font = $invoice->checkPaid() ? 'green' : 'red';
                else
                    $font = 'black';
                $contractTable.=' <tr>
        <td align="right" width="150px" style="color:' . $font . '">
          ' . $invoice->invoicetype . '
        </td>
        <td  align="left"  width="260px" style="color:' . $font . '">
         ' . $invoice->invoice . '
        </td>
        <td align="right" width="100px" style="color:' . $font . '">
          ' . $invoice->invoicedate . '
        </td>
        <td align="right" width="75px" style="color:' . $font . '" >
         ' . number_format($invoiceAmountWithDiscount, 2) . '
        </td>
        <td align="right" width="75px" style="color:' . $font . '" >
         ' . number_format($payment, 2) . '
        </td>
        </tr>';
                $invSum+= $invoiceAmountWithDiscount;
            }
            $contractTable.=  '<tr><td><br></td><td><br></td></tr>
              <tr >
        <td style="border-top: 1px double black;"colspan="2" width ="500px"align="left"><i>Total</i></td>
        <td colspan="2" style="border-top: 1px double black;" width ="85px" align="right">'.number_format($invSum,2).'</td>
        </tr>
        </table><br/>';
            $contractTotal+= $invSum;

            $contractTotal+= $invSum;
        }
        $paymentNumber = number_format(- $totalPayment,2);
        $contractTable.='<hr/><br/><br/>';
        $contractTable.='<table>
            <tr>
                <td width="430px" align="left">
                    <b>Pre-Quote</b>
                </td>
                <td width="230px" align="right">
                    <b> $ '.number_format($totalPq,2).'</b>
                </td>
            </tr>
            <tr>
                <td width="430px" align="left">
                    <b>Billed</b>
                </td>
                <td width="230px" align="right">
                    <b> $ '.number_format($billed,2).'</b>
                </td>
            </tr>
            <tr>
                <td style="border-top: 1px double black;" width="430px" align="left">
                    <b>Not Billed</b>
                </td>
                <td style="border-top: 1px double black;" width="230px" align="right">
                    <b> $ '.number_format(($totalPq - $billed),2).'</b>
                </td>
            </tr>
            </table>
            ';

        $contractTable.='<table>
            <tr><td><br/><br/></td></tr>
            <tr>
                <td width="430px" align="left">
                    <b>Billed</b>
                </td>
                <td width="230px" align="right">
                    <b> $ '.number_format($billed,2).'</b>
                </td>
            </tr>
            <tr>
                <td width="430px" align="left">
                    <b>Payments</b>
                </td>
                <td width="230px" align="right">
                    <b> $ -'.$paymentNumber.'</b>
                </td>
            </tr>
            <tr style="border-top:1px solid black">
                <td style="border-top: 1px double black;" width="430px" align="left">
                    <b>Balance due</b>
                </td>
                <td style="border-top: 1px double black;" width="230px" align="right">
                    <b> $ '.number_format(($billed + $totalPayment),2).'</b>
                </td>
            </tr>
            </table>
            ';

        $pdf->writeHTML($contractTable, true, false, true, false, '');
        if ($mail)
        {
            $body = $_POST['message'];
            $address = $_POST['email'];
            $emailArray = explode(',', $address);
            $subject = $_POST['subject'];
            @unlink('pdf/' . $reportName);
            $pdf->Output('pdf/' . $reportName, 'F');
            $attachment = 'pdf/'.$reportName;
            if (!EmailUtil::sendEmail($subject,$emailArray,$body,$attachment))
            {
                $result = array('success' => false, 'msg' => $mail->ErrorInfo);
                echo json_encode($result);
            }
            else
            {
                $log = new PrintLog();
                $log->date = date('Y-m-j');
                $log->time = date('h-i-s');
                $log->type = 'Contract Report';
                $log->number = $reportName;
                $log->emailto = $_POST['email'];
                $log->print = 'Yes';
                $log->save();
                $result = array('success' => true, 'msg' => 'Message sent!');
                echo json_encode($result);
            }
        }
        else
        {

            //Close and output PDF document
            $pdf->Output($reportName, 'I');

            $log = new PrintLog();
            $log->date = date('Y-m-j');
            $log->time = date('h-i-s');
            $log->type = 'Contract Report';

            $log->emailto = 'noemail';
            $log->print = 'Yes';
            $log->save();
        }
    }

    public function actionStatement($custno)
    {
        $customer = Customers::model()->findByPk($custno);

        $pdf = new SRPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'ANSI_A', true, 'UTF-8', false);
        $pdf->setCustomer($customer);
        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('Statement Report');
        $pdf->SetSubject('Statement Report');
        $pdf->SetKeywords('');

        $pdf->setPrintHeader(true);
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        // $pdf->setLanguageArray($l);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('dejavusans', '', 10);
        $pdf->AddPage();
        //payments section
        $itemRows = '';
        $criteria = new CDbCriteria();
        $criteria->condition = "customerRefFullName ='$customer->quickbook' and invoiceNo=''";
        $criteria->order = "date, paymentTxnID ASC";
        $criteria->group = 'paymentTxnID';
        $refFullname = '';
        $data = Yii::app()->dbqb->createCommand("SELECT * FROM cc_quickbooks.receivepayment
			where CustomerRef_FullName like '$customer->quickbook%' 
			and TimeCreated like '%2012%';")->queryAll();

        $rs = array();
        if (count($data) > 0)
        {
            $rs['totalCount'] = count($data);
            $rs['type'] = 'QB payments';
            foreach ($data as $i => $item)
            {
                $rs['data'][$i] = $item;
                $rs['data'][$i]['totalAmount'] = 0;
                $rs['data'][$i]['invoiceAmount'] = $rs['data'][$i]['TotalAmount'];
                $rs['data'][$i]['unusedPayment'] = 0;
                $idkey = $item['TxnID'];
                $models = Yii::app()->dbqb->createCommand("SELECT * FROM cc_quickbooks.appliedtotxndetail
											where IDKEY='$idkey';")->queryAll();
                foreach ($models as $model)
                {
                    $rs['data'][$i]['invoiceAmount']+= floatval($model['Amount']);
                    $rs['data'][$i]['invoiceAmount']-= floatval($model['DiscountAmount']);
                    if ($rs['data'][$i]['RefNumber'] == '')
                        $rs['data'][$i]['unusedPayment']+= floatval($item['TotalAmount']);
                }
            }
        }

        $result = array();
        if (!isset($rs['data']))
            $rs['data'] = array();
        foreach ($rs['data'] as $i => $item)
        {
            if ($rs['data'][$i]['RefNumber'] == '')
                // if(true)
            {
                $mkdate = explode('/', $rs['data'][$i]['TxnDate']);
                $result[] = array(
                    'date' => $rs['data'][$i]['TxnDate'],
                    'memo' => 'PMT ' . $rs['data'][$i]['Memo'],
                    'amount' => $rs['data'][$i]['invoiceAmount'],
                    'balance' => $rs['data'][$i]['unusedPayment'],
                    //'mktime' => mktime(0, 0, 0, $mkdate[0], $mkdate[1], $mkdate[2]),
                    'mktime' => $rs['data'][$i]['TxnDate'],
                    'type' => 'tr',
                    'dd' => FALSE
                );
            }
        }

        //Invoices

        $criteria = new CDbCriteria();
        $invType = Invoice::TYPE_INVOICE;
        $criteria->condition = "custno='$customer->custno' and invoicetype='$invType'";
        $criteria->order = "invoicedate DESC";
        $invoices = Invoice::model()->findAll($criteria);

        foreach ($invoices as $item)
        {
            if (!$item->checkPaid())
            {
                $mkdate = explode('-', $item->invoicedate);
                $result[] = array(
                    'date' => $item->invoicedate,
                    'memo' => 'I: ' . $item->invoice . ' Due: ' . $item->duedate . ' Org. Amt: ' . $item->amountcharge,
                    'amount' => $item->getAmountWithDiscount(),
                    'balance' => $item->getBalanceDue(),
                    'mktime' => mktime(0, 0, 0, $mkdate[1], $mkdate[2], $mkdate[0]),
                    'type' => 'tr',
                    'dd' => $item->duedate
                );
            }
        }

        //Credit Memo
        $cm = Invoice::TYPE_CREDIT_MEMO;
        $criteria = new CDbCriteria();
        $criteria->condition = "custno='$customer->custno' and invoicetype='$cm'";
        $criteria->order = "invoicedate DESC";
        $invoices = Invoice::model()->findAll("custno='$customer->custno' and invoicetype='$cm'");

        foreach ($invoices as $item)
        {
            if (!$item->checkPaid())
            {
                $mkdate = explode('-', $item->invoicedate);
                $result[] = array(
                    'date' => $item->invoicedate,
                    'memo' => 'CM: ' . $item->invoice . ' Org. Amt: ' . $item->amountcharge,
                    'amount' => $item->getAmountWithDiscount(),
                    'balance' => $item->getBalanceDue(),
                    'mktime' => mktime(0, 0, 0, $mkdate[1], $mkdate[2], $mkdate[0]),
                    'type' => 'cm',
                    'dd' => $item->duedate
                );
            }
        }
        uasort($result, 'sort_array_by_mktime');

        $itemRows = '';
        $ad = 0;
        $amountCurrent = 0;
        $amount30 = 0;
        $amount60 = 0;
        $amount90 = 0;
        $amountOver90 = 0;
        $amountDue = 0;
        foreach ($result as $item)
        {
            $amountDue+= $item['amount'];
            $ad += $item['balance'];
            if ($item['dd'])
            {
                $date = new DateTime();
                $mkdate = explode('-', $item['dd']);
                $date->setTimestamp(mktime(0, 0, 0, $mkdate[1], $mkdate[2], $mkdate[0]));
                $interval = $date->diff(New DateTime);
                $dayDiff = $interval->days;

                if ($dayDiff < 30 && $dayDiff > 0)
                {
                    $amount30+=$item['balance'];
                }
                elseif ($dayDiff < 0)
                {

                    $amountCurrent+=$item['balance'];
                }
                elseif ($dayDiff > 30 && $dayDiff < 60)
                {
                    $amount60+=$item['balance'];
                }
                elseif ($dayDiff > 60 && $dayDiff < 90)
                {
                    $amount90+=$item['balance'];
                }
                elseif ($dayDiff > 90)
                {
                    $amountOver90+=$item['balance'];
                }
            }
            else
            {
                //$amountCurrent+=$item['amount'];
            }
            //  die();


            $itemRows .= '<tr border="1" >
                         <td align="center"  >' . $item['date'] . '</td>
                         <td>' . $item['memo'] . '</td>
                         <td align="right" >' . number_format($item['amount'], 2) . '</td>
                         <td align="right" >' . number_format($ad, 2) . '</td>
                        </tr>';
        }

//die();

        $html = '
    <table  cellspacing="5" cellpadding="5">
     <tr>
        <td style="background-color: #dddddd;border: 1px double black;" colspan="2">Customer Data
</td>
       
    </tr>
    </table>';




        $pdf->writeHTMLCell(181, 0, 15, 45, $html);
        $pdf->writeHTMLCell(150, 0, 16, 58, "&nbsp;<b>$customer->lastname</b>");
        $pdf->writeHTMLCell(150, 0, 17, 62, "<b>$customer->add1</b>");
        if ($customer->add2)
        {
            $pdf->writeHTMLCell(150, 0, 17, 66, "<b>$customer->add2</b>");
            $pdf->writeHTMLCell(150, 0, 17, 72, "<b>$customer->city $customer->state $customer->zip </b>");
        }
        else
        {
            $pdf->writeHTMLCell(150, 0, 17, 66, "<b>$customer->city $customer->state $customer->zip </b>");
        }

        if ($itemRows)
        {
            $html = '<br> <br> <br> <br> <br><br>
            <table   cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="width:68%;"></th>
<th align="center" style="background-color: #dddddd;width:17%;border: 1px double black;">AMOUNT DUE</th>
<th align="center" style="background-color: #dddddd;width:15%;border: 1px double black;">AMOUNT ENC</th>
</tr>
 <tr>
<td></td><td 
style="border: 1px double black;"
align="right" >' . number_format($ad, 2) . '</td>
    <td  style="border: 1px double black;"align="right" >   </td> 
</tr>      </table>     ';

//$pdf->writeHTML($html, true, false, true, false, '');
            $html.='
<table  border = "1" cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #dddddd;width:15%;border: 1px double black;">DATE</th>
<th align="center" style="background-color: #dddddd;width:53%;border: 1px double black;">TRANSACTION</th>
<th align="center" style="background-color: #dddddd;width:17%;border: 1px double black;">AMOUNT</th>
<th align="center" style="background-color: #dddddd;width:15%;border: 1px double black;">BALANCE</th>
</tr>' . "

$itemRows
</table>
";

            $pdf->writeHTML($html, true, false, true, false, '');


            $html = '
<table  cellspacing="0" cellpadding="3" border="1">
<tr>
<th align="center" style="width:16%;">CURRENT</th>
<th align="center" style="width:17%;">1-30 DAYS PAST</th>
<th align="center" style="width:16%;">31-60 DAYS PAST</th>
<th align="center" style="width:17%;">61-90 DAYS PAST</th>
<th align="center" style="width:16%;">OVER 90 DAYS PAST</th>
<th align="center" style="width:18%;">Amount due</th>
</tr>' . '
<tr>
<td align="center" >' . number_format($amountCurrent, 2) . '</td>
<td align="center">' . number_format($amount30, 2) . '</td>
<td align="center">' . number_format($amount60, 2) . '</td>
<td align="center">' . number_format($amount90, 2) . '</td>
<td align="center">' . number_format($amountOver90, 2) . '</td>
<td align="center">' . number_format($ad, 2) . '</td>
</tr>
</table>

';
        }
        else
        {
            $html = '<br><br/><br/><h1>Customer Balance: $0.00 no report to generate at this time.</h1>';
        }

        $pdf->writeHTML($html, true, false, true, false, '');


        // set color for background
        $pdf->SetFillColor(255, 255, 215);

        // set font
        $pdf->SetFont('helvetica', '', 8);


        // reset pointer to the last page
        $pdf->lastPage();


        $reportName = $customer->custno . '-AR-Statement-' . date('Y-m-d') . '.pdf';

        $pdf->Output($reportName, 'I');
    }

    public function actionIndex($invno, $mail = false)
    {
        $pdf = InvoicePdfUtil::getInvoicePdf($invno);
        $invoice = Invoice::model()->findByPk($invno);
        if ($pdf == NULL)
        {
            return true;
        }
        $locationText = StringUtil::removeSpecialCharacter($invoice->location->locname).'_'.StringUtil::removeSpecialCharacter($invoice->location->add1);
        if(isset($_REQUEST['list']) && $_REQUEST['list']==1){
            $filename = 'pdf/'.$locationText.'_'.'PackingList'.'_'.$invoice->invoice.'.pdf';
        }else{
            $filename = 'pdf/'.$locationText.'_'.StringUtil::removeSpecialCharacter($invoice->invoicetype).'_'.$invoice->invoice.'.pdf';
        }



        if ($mail)
        {

            $body = $_POST['message'];
            $address = $_POST['email'];
            $emailArray = explode(',', $address);
            $subject = $_POST['subject'];
            @unlink($filename);
            $pdf->Output($filename, 'F');
            $attachment = $filename;


            if (! EmailUtil::sendEmail($subject,$emailArray,$body,$attachment))
            {

                $result = array('success' => false, 'msg' => $mail->ErrorInfo);
                echo json_encode($result);
            }
            else
            {
                $log = new PrintLog();
                $log->date = date('Y-m-j');
                $log->time = date('h-i-s');
                $log->type = $invoice->invoicetype . ' Report';
                $log->number = $invno;
                $log->emailto = $_POST['email'];
                $log->print = 'Yes';
                $log->save();
                $result = array('success' => true, 'msg' => 'Message sent!');
                echo json_encode($result);
            }
        }
        else
        {
            //Close and output PDF document
            $pdf->Output($filename, 'I');
            //   $pdf->Output('inv-' . time(), 'I');
            $log = new PrintLog();
            $log->date = date('Y-m-j');
            $log->time = date('h-i-s');
            $log->type = 'Invoice Report';
            $log->number = $invno;
            $log->emailto = 'noemail';
            $log->print = 'Yes';
            $log->save();
        }

        //============================================================+
        // END OF FILE
        //============================================================+
        //

    }





    public function actionDep()
    {

        $pdf = new InvPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $account = $_REQUEST['data']['account'];
        $deposit = $_REQUEST['data']['deposit'];
        $date = $_REQUEST['data']['date'];
        $memo = $_REQUEST['data']['memo'];

        $recledlist = $_REQUEST['list'];
        if (count($recledlist) > 18)
        {
            throw new CHttpException('You can not select more then 18 checks');
        }
        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('Deposit');
        $pdf->SetSubject('Deposit');
        $pdf->SetKeywords('');


        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        // $pdf->setLanguageArray($l);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('dejavusans', '', 10);

        //start point :1344,87 ->amount point: +160, below:+82
        $pdf->AddPage();



        //$pdf->writeHTMLCell(200.5, 60, 160, 80, $html);
        $pdf->writeHTMLCell(25, 25, 12, 40, date('m/d/Y'));

        $count = 0;



        $rows = '';
        $subtotal = 0;

        $x = 65;
        $y = 12;
        $column = 1;
        $row = 1;

        foreach ($recledlist as $item)
        {
            $item = RecLed::model()->findByPk($item);
            $count++;
            $pdf->writeHTMLCell(25, 25, $x, $y, "$count");
            $pdf->writeHTMLCell(25, 25, $x + 10, $y, "{$item->amount}");
            $y+=9;
            $row++;
            if (($column == 1 && $row == 7) || ($column == 2 && $row == 8 ) || ($column == 3 && $row == 5))
            {
                $y = 16;
                $x+=50;
                $column++;
                $row = 1;
            }
            $cusname = '';
            if ($item->customer != null)
            {
                $cusname = $item->customer->firstname . ' ' . $item->customer->lastname;
            }
            if (strlen($cusname) > 40)
            {
                $cusname = substr($cusname, 0, 17) . '...';
            }
            if (strlen($memo) > 20)
            {
                $memo = substr($memo, 0, 17) . '...';
            }

            $rows .= '
             <tr>
             <td>' . $item->ckno . '</td>
             <td>' . PaymentMethods::getDesc($item->paymethod) . '</td>
             <td>' . $cusname . '</td>
             <td>' . $memo . '</td>
             <td>' . $item->amount . '</td>
             </tr>
             ';
            $subtotal += $item->amount;
        }
        $pdf->writeHTMLCell(25, 25, 189, 41, $subtotal);
        $pdf->writeHTMLCell(25, 25, 189, 50, '0.00');
        $pdf->writeHTMLCell(25, 25, 144, 72, count($recledlist));
        $pdf->writeHTMLCell(25, 25, 175, 72, $subtotal);
        $html = '  <h2>Deposit Summary  ' . $deposit . '</h2>        <br>
                Summary of deposit to Checking  ' . date('m/d/Y');

        $pdf->writeHTMLCell(200.5, 60, 10, 90, $html);
        $html = '
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="left" style="width:15%"><b>Chk no</b></th>
<th align="left" style="width:15%" ><b>Pmt Method</b></th>
<th align="left" style="width:25%" ><b>Rcd From</b></th>
<th align="left" style="width:30%" ><b>Memo</b></th>
<th align="left"  style="width:15%"><b>Amount</b></th>
</tr>
' . $rows . '
</table>

';
        $pdf->writeHTMLCell(200.5, 60, 10, 105, $html);
        //  echo $html;
        $subtotalInfoHtml = "<b>Deposit Subtotal: </b>";
        $taxInfoHtml = "<b>Less Cash Bback</b>";
        $totalInfoHtml = "<b>Deposit Total:</b>";

        $subtotal = number_format($subtotal, 2);
        $subtotalHtml = '<b  style="text-align:right;">' . $subtotal . '</b>';
        $taxHtml = '<b  style="text-align:right;">0.00</b>';
        $totalHtml = '<b  style="text-align:right;">' . $subtotal . '</b>';
        $pdf->writeHTMLCell(75, 0, 33, 268, $subtotalInfoHtml);
        $pdf->writeHTMLCell(75, 0, 33, 272, $taxInfoHtml);
        $pdf->writeHTMLCell(75, 0, 33, 276, $totalInfoHtml);
        $pdf->writeHTMLCell(25, 0, 170, 268, $subtotalHtml);
        $pdf->writeHTMLCell(25, 0, 170, 272, $taxHtml);
        $pdf->writeHTMLCell(25, 0, 170, 276, $totalHtml);

        // set color for background
        $pdf->SetFillColor(255, 255, 215);

        // set font
        $pdf->SetFont('helvetica', '', 8);


        // reset pointer to the last page
        $pdf->lastPage();


        // reset pointer to the last page
        $pdf->lastPage();


        // ---------------------------------------------------------
        $name = 'pdf/dep-' . time() . '.pdf';
        //Close and output PDF document
        $pdf->Output($name, 'F');
        $this->redirect($name);
    }

    public function actionPO($pono, $mail = false)
    {
        $po = Po::model()->findByPk($pono);

        $customer = Customers::model()->findByPk($po->custno);
        $location = Locations::model()->find('custno=:custno and locno=:locno',array(
            'custno'=>$po->custno,
            'locno'=>$po->locno
        ));
        $pdf = new PoPdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('PO #' . $po->pono);
        $pdf->SetSubject('PO');
        $pdf->SetKeywords('');
        $date = explode(' ', $po->date);
        $pdf->setMyHeaderData($po->pono, $date[0], $po->custno);
        $pdf->setInvoiceType('PO');

        $pdf->setPrintHeader(true);
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        // $pdf->setLanguageArray($l);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('dejavusans', '', 10);


        $pdf->AddPage();
        $itemRows = '';
        $subtotal = 0;
        $poItems = PoLedger::model()->findAll((array(
            'condition' => 'pono=:pono',
            'params' => array(
                'pono' => $po->pono
            )
        )));

        $tax = 0;
        foreach ($poItems as $item)
        {
            $amount = $item->price * $item->qty;

            $itemRows .= '<tr>
                         <td align="center"  >' . $item->partno . '</td>
                         <td align="center"  >' . $item->qty . '</td>
                         <td>' . $item->description . '</td>
                         <td align="right" >' . $item->price . '</td>
                         <td align="right" >' . number_format($amount, 2) . '</td>
                        </tr>';
            $subtotal += $amount;
        }


        $html = '
    <table border="0" cellspacing="5" cellpadding="5">
     <tr>
        <td style="background-color: #888888;border: 1px double black;" colspan="2">Vendor</td>
        <td style="background-color: #888888;border: 1px double black;" colspan="2">Ship to</td>
    </tr>
    </table>';

        $vendor = Vendors::model()->findByPK($po->vendor);
        //writeHTMLCell ($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true)
        //  $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->writeHTMLCell(181, 0, 15, 45, $html);
        $pdf->writeHTMLCell(150, 0, 16, 58, "<b>$vendor->company</b>");
        if ($vendor->add2)
        {
            $pdf->writeHTMLCell(150, 0, 16, 62, "<b>$vendor->add1</b>");
            $pdf->writeHTMLCell(150, 0, 16, 66, "<b>$vendor->add2</b>");
            $pdf->writeHTMLCell(150, 0, 16, 72, "<b>$vendor->city $vendor->state $vendor->zip </b>");
        }
        else
        {
            $pdf->writeHTMLCell(150, 0, 16, 62, "<b>$vendor->add1</b>");
            $pdf->writeHTMLCell(150, 0, 16, 66, "<b>$vendor->city $vendor->state $vendor->zip </b>");
        }

        $pdf->writeHTMLCell(150, 0, 106, 58, "<b>$location->locname</b>");
        if ($po->shipaddress2)
        {
            $pdf->writeHTMLCell(150, 0, 106, 62, "<b>$po->shipaddress1</b>");
            $pdf->writeHTMLCell(150, 0, 106, 66, "<b>$po->shipaddress2</b>");
            $pdf->writeHTMLCell(150, 0, 106, 70, "<b>$po->shipaddress3</b>");
        }
        else
        {
            $pdf->writeHTMLCell(150, 0, 106, 62, "<b>$po->shipaddress1</b>");
            $pdf->writeHTMLCell(150, 0, 106, 66, "<b>$po->shipaddress3</b>");
        }

        $termsList = Customers::model()->getTermList();
        $dateExp = explode(' ', $po->datereq);
        $date = explode('-', $dateExp[0]);
        $timepstamp = mktime(0, 0, 0, $date[1], $date[2], $date[0]);
        $formattedDate = date('m-d-Y', $timepstamp);

        $shippingData =  Dropdowns::getList('POShipVia');
        $shipType =  Dropdowns::getList('POShippingType');
        $html = '  <br> <br> <br><br>

<table  cellspacing="0" cellpadding="1" border="1">
    <tr>
    <th align="center" style="background-color: #888888;border: 1px double black;">SHIP VIA</th>  
      <th align="center" style="background-color: #888888;border: 1px double black;">SHIP TYPE</th>
    <th align="center" style="background-color: #888888;border: 1px double black;">BUYER</th>

     <th  align="center" style="background-color: #888888;border: 1px double black;">TERMS</th>
     <th  align="center" style="background-color: #888888;border: 1px double black;">DATE EXPECTED</th>
    </tr>
    <tr>
         <td align="center"  >' . $shippingData[$po->shipvia] . '</td>
         <td align="center" >'  . Dropdowns::getText('POShippingType',$po->shiptype). '</td>
        <td align="center"  >' . Employees::getEmployeeName($po->buyer) . '</td>
        <td align="center"  >' . $termsList[$po->terms] . '</td>
        <td align="center"  >' . $formattedDate . '</td>

    </tr>
</table>
         <br>
<table  cellspacing="0" cellpadding="3" >
<tr>
<th align="center" style="background-color: #888888;width:20%;border: 1px double black;">PART NO</th>
<th align="center" style="background-color: #888888;width:10%;border: 1px double black;">QTY</th>
<th align="center" style="background-color: #888888;width:48%;border: 1px double black;">DESCRIPTION</th>
<th align="center" style="background-color: #888888;width:12%;border: 1px double black;">PRICE EACH</th>
<th align="center" style="background-color: #888888;width:10%;border: 1px double black;">AMOUNT</th>
</tr>' . "

$itemRows
</table>

";
        //  echo $html;
        $pdf->writeHTML($html, true, false, true, false, '');


        $totalInfoHtml = "<b>Total:</b>";
        $total = $subtotal;


        $totalHtml = '<b>' . number_format($total, 2) . '</b>';

        $pdf->writeHTMLCell(25, 0, 33, 276, $totalInfoHtml);

        $pdf->writeHTMLCell(25, 0, 180, 276, $totalHtml);

        // set color for background
        $pdf->SetFillColor(255, 255, 215);

        // set font
        $pdf->SetFont('helvetica', '', 8);


        // reset pointer to the last page
        $pdf->lastPage();


        if ($mail)
        {
            $body = $_POST['message'];
            $address = $_POST['email'];
            $emailArray = explode(',', $address);
            $subject = $_POST['subject'];
            $pdf->Output('pdf/po-' . $po->pono . '.pdf', 'F');
            $attachment = 'pdf/po-' . $po->pono . '.pdf';
            if (! EmailUtil::sendEmail($subject,$emailArray,$body,$attachment))
            {

                $result = array('success' => false, 'msg' => $mail->ErrorInfo);
                echo json_encode($result);
            }
            else
            {
                $log = new PrintLog();
                $log->date = date('Y-m-j');
                $log->time = date('h-i-s');
                $log->type = 'Payment Order';
                $log->number = $po->pono;
                $log->emailto = $_POST['email'];
                $log->print = 'Yes';
                $log->save();
                $result = array('success' => true, 'msg' => 'Message sent!');
                echo json_encode($result);
            }
        }
        else
        {
            //Close and output PDF document
            $pdf->Output('po-' . $po->pono, 'I');
            $log = new PrintLog();
            $log->date = date('Y-m-j');
            $log->time = date('h-i-s');
            $log->type = 'Payment Order';
            $log->number = $pono;
            $log->emailto = '';
            $log->print = 'Yes';
            $log->save();
        }

        // ---------------------------------------------------------
        //============================================================+
        // END OF FILE
        //============================================================+
    }

    protected function calculateInvoiceEarnedRevenue($item, &$data)
    {

        $startDate = new DateTime($item['contractstartdate']);
        $endDate = new DateTime($item['contractenddate']);
        $endDate->add(new DateInterval('P1D'));
        $curDate = new DateTime('now');
        $contractAmount = $item['contractamount'];
        $startMonth = $startDate->format('m');
        if ($item['contractype'] == Contracts::TYPE_MONTHLY || $item['contractype'] == Contracts::TYPE_QUARTERLY)
        {
            $contractMonthDiff = $startDate->diff($endDate, true);
            $monthPassDiff = $curDate->diff($startDate);
            $contractMonth = $contractMonthDiff->format('%y') * 12 + $contractMonthDiff->format('%m');
            $monthPass = $monthPassDiff->format('%y') * 12 + $monthPassDiff->format('%m');
        }
        else
        {
            $contractMonth = 12;
            $monthPassDiff = $curDate->diff($startDate);
            $monthPass = $monthPassDiff->format('%y') * 12 + $monthPassDiff->format('%m');
        }
        if (time() > strtotime($item['contractenddate']))
        {

            $data['revenue'] = $contractAmount;
        }
        else
        {
            //$amount = $contractAmount / $contractMonth * $monthPass;
            $data['revenue'] = $contractAmount / $contractMonth * $monthPass;
        }
        if ($contractMonth > 0)
        {

            $data['revenueByMonths'] = $this->getRevenueByMonth($contractAmount / $contractMonth, $startMonth, $monthPass, $contractMonth);
        }
    }

    protected function getRevenueByMonth($amountPerMonth, $startMonth, $monthPass, $contractMonth)
    {


        $rs = array();
        //$startMonth++;
        for ($i = 1; $i <= 24; $i++)
        {
            if ($i >= $startMonth && $i < $startMonth + $monthPass && $i < $contractMonth + $startMonth)
            {
                $rs[$i] = $amountPerMonth;
            }
            else
            {
                $rs[$i] = 0;
            }
        }

        return $rs;
    }

    public function actionEarnedRevenueReport()
    {
        if (isset($_GET['year']) && is_numeric($_GET['year']))
        {
            $year = $_GET['year'];
            $invoiceData = Yii::app()->db->createCommand('
            SELECT i.*,c.*,l.*
            FROM tbl_contracts c
            INNER JOIN tbl_locations l ON l.locno = c.locno AND l.custno = c.custno
            left join tbl_invoice i on c.contractid= i.agreementno
            WHERE i.invoicetype = :invoicetype
            and i.agreementno!=""
            AND year(c.contractstartdate) = :year             
            group by c.contractid
            ORDER BY l.state
            ')->bindValues(array(
                    'year' => $year,
                    'invoicetype' => Invoice::TYPE_INVOICE
                ))->queryAll();
            if (count($invoiceData) == 0)
            {
                echo 'There are no data to show';
                exit;
            }
            foreach ($invoiceData as $i => $item)
            {

                $rs[$i] = $item;
                $this->calculateInvoiceEarnedRevenue($item, $rs[$i]);

                if (time() > strtotime($item['contractenddate']) || $rs[$i]['revenue'] == $rs[$i]['contractamount'])
                {
                    $rs[$i]['isExpired'] = true;
                }
                else
                {
                    $rs[$i]['isExpired'] = false;
                }
            }


            $grandAmount = 0;
            $grandEarned = 0;
            $grandRevenueByMonths = array();
            $data = array();

            foreach ($rs as $i => $item)
            {
                $data[$item['state']]['items'][] = $item;
                if (!isset($data[$item['state']]['revenue']))
                {
                    $data[$item['state']]['revenue'] = $item['revenue'];
                }
                else
                {
                    $data[$item['state']]['revenue'] +=$item['revenue'];
                }

                if (!isset($data[$item['state']]['amount']))
                {
                    $data[$item['state']]['amount'] = $item['contractamount'];
                }
                else
                {
                    $data[$item['state']]['amount']+=$item['contractamount'];
                }

                for ($month = 1; $month <= 24; $month++)
                {
                    if (isset($item['revenueByMonths']))
                    {
                        $amount = $item['revenueByMonths'][$month];
                        if (!isset($data[$item['state']]['revenueByMonths'][$month]))
                        {
                            $data[$item['state']]['revenueByMonths'][$month] = $amount;
                        }
                        else
                        {
                            $data[$item['state']]['revenueByMonths'][$month]+=$amount;
                        }
                        if (!isset($grandRevenueByMonths[$month]))
                        {
                            $grandRevenueByMonths[$month] = $amount;
                        }
                        else
                        {
                            $grandRevenueByMonths[$month]+=$amount;
                        }
                    }
                }

                $grandAmount+=$item['contractamount'];
                $grandEarned+=$item['revenue'];
            }

            $this->layout = '//layouts/space';
            $this->render('earnedRevenueReport', array(
                'data' => $data,
                'grandAmount' => $grandAmount,
                'grandRevenue' => $grandEarned,
                'grandRevenueByMonths' => $grandRevenueByMonths
            ));
        }
        else
        {
            $yearList = Yii::app()
                ->db
                ->createCommand('SELECT DISTINCT YEAR(  `contractstartdate` ) `contractYear` fROM  `tbl_contracts` order by `contractYear`')
                ->queryAll();
            $this->render('earnedRevenueReportForm', array('yearList' => $yearList));
        }
    }

    public function actiontaxreport($startdate = Null, $enddate = Null)
    {

        $this->layout = '//layouts/space';

        $startDateArr = explode('/', $startdate);
        $start = '';
        if (count($startDateArr) == 3)
        {
            $start = $startDateArr[2] . '-' . $startDateArr[0] . '-' . $startDateArr[1];
            if (isDateValid($start) == false)
            {
                throw new CHttpException('Invalid start date');
            }
        }
        else
        {
            throw new CHttpException('Invalid start date');
        }
        $endDateArr = explode('/', $enddate);
        $end = '';
        if (count($endDateArr) == 3)
        {
            $end = $endDateArr[2] . '-' . $endDateArr[0] . '-' . $endDateArr[1];
            if (isDateValid($end) === false)
            {
                throw new CHttpException('Invalid end date');
            }
        }
        else
        {
            throw new CHttpException('Invalid end date');
        }
        $departments = null;
        if (isset($_GET['department']))
        {
            $departments = $_GET['department'];
            $departmentSql = implode(',', $departments);
        }
        else
        {
            $departmentSql = '';
        }


        $sql = 'SELECT i.*,l.isexempt,l.county,l.locname,l.state
                    FROM tbl_invoice i     
                    inner join tbl_locations l on l.custno = i.custno and l.locno = i.locno                    
                    WHERE (i.invoicetype = :invoicetype or i.invoicetype=:creditmemo)
                    and (i.agreementno ="" or (i.agreementno!="" and i.department not in ("05","07","08")))
                    AND i.invoicedate BETWEEN :start AND :end';

        if ($departments != null)
        {
            $sql.=' AND i.department in (' . $departmentSql . ')';
        }
        $sql.=' order by l.state';



        $invoiceData = Yii::app()->db->createCommand($sql)->bindValues(array(
            'start' => $start,
            'end' => $end,
            'invoicetype' => Invoice::TYPE_INVOICE,
            'creditmemo' => Invoice::TYPE_CREDIT_MEMO
        ))->queryAll();
        $this->transformAndRenderTaxContractData($invoiceData, $startdate, $enddate, $departments);
    }

    public function actionTaxReportByState($state)
    {
        $this->layout = '//layouts/space';
        $sql = 'SELECT i.*,l.isexempt,l.county,l.locname,l.state
                    FROM tbl_invoice i     
                    inner join tbl_locations l on l.custno = i.custno and l.locno = i.locno                  
                    WHERE (i.invoicetype = :invoicetype or i.invoicetype=:creditmemo
                    and (i.agreementno ="" or (i.agreementno!="" and i.department not in ("05","07","08")))
                    AND l.state =:state
                    order by l.state';
        $invoiceData = Yii::app()->db->createCommand($sql)->bindValues(array(
            'state' => $state,
            'invoicetype' => Invoice::TYPE_INVOICE,
            'creditmemo' => Invoice::TYPE_CREDIT_MEMO
        ))->queryAll();
        $this->transformAndRenderTaxContractData($invoiceData);
    }

    protected function transformAndRenderTaxContractData($invoiceData, $start = null, $end = null, $departments = null)
    {
        if (count($invoiceData) == 0)
        {
            return;
        }
        $rs = array();
        $rs['totalCount'] = count($invoiceData);

        foreach ($invoiceData as $i => $item)
        {
            $model = Invoice::model()->findByPk($item['invoice']);
            //$model->attributes = $item;
            $rs['data'][$i] = $item;
            $dateExp = explode(' ', $model->invoicedate);
            $date = explode('-', $dateExp['0']);
            $timepstamp = mktime(0, 0, 0, $date[1], $date[2], $date[0]);
            $rs['data'][$i]['fdate'] = date('m/d/Y', $timepstamp);
            $rs['data'][$i]['tax'] = $model->getTaxAmount();
            $rs['data'][$i]['exempt'] = $model->getExemptAmount();

            $csz = $rs['data'][$i]['shipCSZ'];
            $csz = trim($csz);
            $pos = strrpos($csz, ' ');

            $zip = substr($csz, $pos + 1, 5);
            if ($model->checkNex())
            {
                $taxRate = Yii::app()
                    ->db
                    ->createCommand('select nextaxrate from tbl_taxcode where zipcode=:zipcode')
                    ->bindValue('zipcode', $zip)->queryScalar();
            }
            else
            {
                $taxRate = Yii::app()
                    ->db
                    ->createCommand('select salestaxrate from tbl_taxcode where zipcode=:zipcode')
                    ->bindValue('zipcode', $zip)->queryScalar();
            }
            $isNex = $model->checkNex();
            if($isNex){
                $rs['data'][$i]['taxrate'] = $model->getTaxModel()->nextaxrate;
            }else{
                $rs['data'][$i]['taxrate'] = $model->getTaxModel()->salestaxrate;
            }

            $taxTest = 0;
            if ($rs['data'][$i]['isexempt'] != -1)
            {
                $taxTest = ($rs['data'][$i]['amountcharge'] - $rs['data'][$i]['tax'] - $rs['data'][$i]['exempt']) * ($taxRate / 100);

                if($model->invoicetype == Invoice::TYPE_CREDIT_MEMO){
                    $taxTest = -abs($taxTest);
                }
                $taxTest = round($taxTest, 2);
            }
            // $rs['data'][$i]['tax']      = $taxTest;
            $totalTax = $model->getTotalTax();
            $test = round(abs($rs['data'][$i]['tax']) - abs($totalTax));
            $rs['data'][$i]['taxtest'] = $totalTax;
            $rs['data'][$i]['test'] = $test;
        }
        //echo json_encode($rs);
        $oldTaxcode = '';
        $totalTax = 'none';
        $totalAmount = 'none';
        $totalExempt = 'none';
        $newRowFlag = false;
        $viewData = array();
        $grandAmount = 0;
        $grandTax = 0;
        $grandExempt = 0;
        $grandTaxTest = 0;
        $grandTest = 0;
        foreach ($rs['data'] as $index => $item)
        {
            $grandAmount += $item['amountcharge'];
            $grandExempt += $item['exempt'];
            $grandTax += $item['tax'];
            $grandTaxTest += $item['taxtest'];
            $grandTest +=$item['test'];
            $viewData[$item['state']]['items'][] = $item;
            if (!isset($viewData[$item['state']]['amount']))
            {
                $viewData[$item['state']]['amount'] = $item['amountcharge'];
            }
            else
            {
                $viewData[$item['state']]['amount'] +=$item['amountcharge'];
            }

            if (!isset($viewData[$item['state']]['tax']))
            {
                $viewData[$item['state']]['tax'] = $item['tax'];
            }
            else
            {
                $viewData[$item['state']]['tax'] +=$item['tax'];
            }

            if (!isset($viewData[$item['state']]['exempt']))
            {
                $viewData[$item['state']]['exempt'] = $item['exempt'];
            }
            else
            {
                $viewData[$item['state']]['exempt'] +=$item['exempt'];
            }

            if (!isset($viewData[$item['state']]['taxtest']))
            {
                $viewData[$item['state']]['taxtest'] = $item['taxtest'];
            }
            else
            {
                $viewData[$item['state']]['taxtest'] +=$item['taxtest'];
            }

            if (!isset($viewData[$item['state']]['test']))
            {
                $viewData[$item['state']]['test'] = $item['test'];
            }
            else
            {
                $viewData[$item['state']]['test'] +=$item['test'];
            }
        }
        $this->render('taxreport', array(
            'viewData' => $viewData,
            'grandAmount' => $grandAmount,
            'grandTax' => $grandTax,
            'grandExempt' => $grandExempt,
            'grandTaxTest' => $grandTaxTest,
            'grandTest' => $grandTest,
            'startDate' => $start,
            'endDate' => $end,
            'departments' => $departments
        ));
    }

    public function actionjob($jobid)
    {
        $pdf = new JobPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $job = Jobs::model()->findByPk($jobid);
        $html = false;
        $item = $job->getAttributes();
        $item ['locname'] = $job->location->locname;
        $item ['locno'] = $job->location->locno;
        $item ['add1'] = $job->location->add1;
        $item ['csz'] = $job->location->city . ' ' . $job->location->state . ' ' . substr($job->location->zip, 0, 5);
        $item ['billingstatustext'] = JobsBillingStatus::getText($job->billingstatus);
        $item ['jobstatustext'] = JobsStatus::getText($job->jobstatus);
        $item ['quotelist'] = $job->quoteList;
        $item ['invoicelist'] = $job->invoiceList;
        $item ['salesorderslist'] = $job->salesOrderList;
        $html .= '     <br>
        <table  style="width: 925px;"  cellspacing="0"  cellpadding="2" >
            <tr>
                <td align="left" style="border-bottom:  2px solid  black;width:100px;">
                <b>  Job  </b>
                </td>
                <td align="left" style="border-bottom: 2px solid  black;width:200px;">
                 <b> Customer   Info </b>
                </td>

                <td align="left" style="border-bottom:  2px solid  black;width:200px;">
                   <b>   Address   </b>
                </td>
                <td align="left"  style="border-bottom:  2px solid  black;width:100px;" >
                  <b>    Job Status        </b>
                </td>
                <td align="left"  style="border-bottom:  2px solid  black;width:290px;"   >
                   <b>  Job Descrition  </b>
                </td>
            </tr>
            <tr>
                <td align="left">
                    &nbsp;' . $item['jobid'] . '
                </td>
                <td align="left">
                   ' . $item['custno'] . ' - ' . $item['locno'] . ' <br/>
                  &nbsp;   ' . $item['locname'] . '
                </td>

                <td align="left" >
                   &nbsp;       ' . $item['add1'] . '<br>
                   &nbsp;   ' . $item['csz'] . '
                </td align="left" >
                <td align="left" >
                   &nbsp;   ' . $item['jobstatustext'] . '
                </td >
                <td align="left"  >
                   &nbsp;' . $item['description'] . '
                </td>
            </tr>
            </table>  ';
        $html .= '<br>
            <table style="width: 900px;" cellspacing="0"  cellpadding="2" >
            <tr>
                <td align="left" style="width:90px;" >
                 <b>   Date     </b>
                </td>
                <td align="left" style="width:100px;" >
                 <b>   Type     </b>
                </td>
                <td align="left" style="width:100px;"  >
                 <b>    Reference   </b>
                </td>
                <td align="left" style="width:80px;"  >
                <b>     Number   </b>
                </td>
                <td align="left" style="width:80px;"  >
                <b>     Status   </b>
                </td>
                <td align="right" style="width:160px;" >
                 <b>   Total Amount   </b>
                </td>
                <td align="right" style="width:120px;" >
                 <b>  Amount  Paid     </b>

                </td>

                <td align="right" style="width:160px;" >
                 <b>     Remaining Balance     </b>
                </td>

            </tr>

        ';
        if (count($item['quotelist']))
        {

            $html .= $pdf->parseInvoices($item['quotelist']);
        }
        if (count($item['invoicelist']))
        {

            $html .= $pdf->parseInvoices($item['invoicelist']);
        }
        if (count($item['salesorderslist']))
        {


            $html .= $pdf->parseInvoices($item['salesorderslist']);
        }
        $html .= ' </table>
                  <h4  style="text-decoration:underline;" >Billing Status: ' . JobsBillingStatus::getText($item['billingstatus']) . '</h4>';
        $html .= <<<HERE
              <h4  style="text-decoration:underline;" >Payments</h4>
              <table  cellspacing="3"  style="width: 925px;" >
              <tr>
                <th align = "left" style="width:80px;" >
                 <b>Date</b>
                </th>
                <th align = "left" style="width:80px;" >
                  <b> Type </b>
                </th>
                <th align = "left"  style="width:80px;">
                 <b>  Memo </b>
                </th>
                <th align = "left" style="width:160px;" >
                 <b> Payment Amount  </b>
                </th>

              </tr>
              {$pdf->parsePayment($item['invoicelist'])}
              </table>
            <h1></h1>
HERE;

        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('Job Report');
        $pdf->SetSubject('PO');
        $pdf->SetKeywords('');
        $pdf->setPrintHeader(true);
        $pdf->setPrintFooter(false);
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 30, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        // $pdf->setLanguageArray($l);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('dejavusans', '', 8);


        $pdf->AddPage();

        if ($html)
            $pdf->writeHTML($html, true, false, true, false, '');
        else
            $pdf->writeHTML('<h1>No Data Found</h1>', true, false, true, false, '');

        // set color for background
        $pdf->SetFillColor(255, 255, 215);

        // set font
        $pdf->SetFont('helvetica', '', 8);


        // reset pointer to the last page
        $pdf->lastPage();

        $rname = 'cc-jobreport-' . date('m-j-Y-g-i-a') . '.pdf';
        // ---------------------------------------------------------
        // echo $html;
        //Close and output PDF document
        $pdf->Output($rname, 'I');

        //============================================================+
        // END OF FILE
        //============================================================+
    }

    public function actionjobreport($custno, $startdate = null, $end = null, $year = null, $jobsalesperson = null, $sort = NULL, $status = Null)
    {
        $pdf = new JobPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('Job Report');
        $pdf->SetSubject('PO');
        $pdf->SetKeywords('');
        $pdf->setPrintHeader(true);
        $pdf->setPrintFooter(false);
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 30, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        // $pdf->setLanguageArray($l);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('dejavusans', '', 8);
        $pdf->AddPage();
        $criteria = new CDbCriteria();

        if ($custno != 'All')
        {
            $criteria->condition = 'custno=:custno';
            $criteria->params = array(
                'custno' => $custno);
        }
        if ($status != 'All')
        {
            $criteria->addColumnCondition(array('jobstatus' => intval($status)));
        }

        if (!empty($startdate) && !empty($end))
        {
            $fstartdate = explode('/', $startdate);
            $startdate = $fstartdate['2'] . '-' . $fstartdate['0'] . '-' . $fstartdate['1'];
            $fend = explode('/', $end);
            $end = $fend['2'] . '-' . $fend['0'] . '-' . $fend['1'];
            $criteria->addBetweenCondition('addeddate', $startdate, $end);
        }
        else if ($year != null)
        {
            $criteria->addColumnCondition(array(
                'year(addeddate)' => $year
            ));
        }

        $criteria->compare('jobsalesperson', $jobsalesperson);
        $pageSize = Jobs::model()->count();
        $data = new CActiveDataProvider('Jobs', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => $pageSize,
            )
        ));

        $html = false;

        if ($data != NULL && count($data->getData()) > 0)
        {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item)
            {

                $rs['data'][$i] = $item->getAttributes();
                $rs['data'][$i]['locname'] = $item->location->locname;
                $rs['data'][$i]['locno'] = $item->location->locno;
                $rs['data'][$i]['add1'] = $item->location->add1;
                $rs['data'][$i]['csz'] = $item->location->city . ' ' . $item->location->state . ' ' . substr($item->location->zip, 0, 5);
                $rs['data'][$i]['billingstatustext'] = JobsBillingStatus::getText($item->billingstatus);
                $rs['data'][$i]['jobstatustext'] = JobsStatus::getText($item->jobstatus);
                $rs['data'][$i]['quotelist'] = $item->quoteList;
                $rs['data'][$i]['invoicelist'] = $item->invoiceList;
                $rs['data'][$i]['salesorderslist'] = $item->salesOrderList;
            }
            //echo json_encode($rs);

            foreach ($rs['data'] as $item)
            {
                $html = '     <br>
        <table  style="width: 925px;"  cellspacing="0"  cellpadding="2" >
            <tr>
                <td align="left" style="border-bottom:  2px solid  black;width:100px;">
                <b>  Job  </b>
                </td>
                <td align="left" style="border-bottom: 2px solid  black;width:200px;">
                 <b> Customer   Info </b>
                </td>

                <td align="left" style="border-bottom:  2px solid  black;width:200px;">
                   <b>   Address   </b>
                </td>
                <td align="left"  style="border-bottom:  2px solid  black;width:100px;" >
                  <b>    Job Status        </b>
                </td>
                <td align="left"  style="border-bottom:  2px solid  black;width:290px;"   >
                   <b>  Job Descrition  </b>
                </td>
            </tr>
            <tr>
                <td align="left">
                    &nbsp;' . $item['jobid'] . '
                </td>
                <td align="left">
                   ' . $item['custno'] . ' - ' . $item['locno'] . ' <br/>
                  &nbsp;   ' . $item['locname'] . '
                </td>

                <td align="left" >
                   &nbsp;       ' . $item['add1'] . '<br>
                   &nbsp;   ' . $item['csz'] . '
                </td align="left" >
                <td align="left" >
                   &nbsp;   ' . $item['jobstatustext'] . '
                </td >
                <td align="left"  >
                   &nbsp;' . $item['description'] . '
                </td>
            </tr>
            </table>  ';
                $html .= '<br>
            <table style="width: 900px;" cellspacing="0"  cellpadding="2" >
            <tr>
                <td align="left" style="width:90px;" >
                 <b>   Date     </b>
                </td>
                <td align="left" style="width:100px;" >
                 <b>   Type     </b>
                </td>
                <td align="left" style="width:100px;"  >
                 <b>    Reference   </b>
                </td>
                <td align="left" style="width:80px;"  >
                <b>     Number   </b>
                </td>
                <td align="left" style="width:80px;"  >
                <b>     Status   </b>
                </td>
                <td align="right" style="width:160px;" >
                 <b>   Total Amount   </b>
                </td>
                <td align="right" style="width:120px;" >
                 <b>  Amount  Paid     </b>

                </td>
                <td align="right" style="width:160px;" >
                 <b>     Remaining Balance     </b>
                </td>
            </tr>
        ';
                if (count($item['quotelist']))
                {
                    $html .= $pdf->parseInvoices($item['quotelist']);
                }
                if (count($item['invoicelist']))
                {
                    $html .= $pdf->parseInvoices($item['invoicelist']);
                }
                if (count($item['salesorderslist']))
                {
                    $html .= $pdf->parseInvoices($item['salesorderslist']);
                }
                $html .= ' </table>
                  <h4  style="text-decoration:underline;" >Billing Status: ' . JobsBillingStatus::getText($item['billingstatus']) . '</h4>';
                //*
                $html .= <<<HERE
              <h4  style="text-decoration:underline;" >Payments</h4>
              <table  cellspacing="3"  style="width: 925px;" >
              <tr>
                <th align = "left" style="width:80px;" >
                 <b>Date</b>
                </th>
                <th align = "left" style="width:80px;" >
                  <b> Type </b>
                </th>
                <th align = "left"  style="width:80px;">
                 <b>  Memo </b>
                </th>
                <th align = "left" style="width:160px;" >
                 <b> Payment Amount  </b>
                </th>

              </tr>
              {$pdf->parsePayment($item['invoicelist'])}
              </table>
            <h1></h1>
HERE;
                //  */
                $pdf->writeHTML($html, true, false, true, false, '');
            }
        }
        //$pdf->AddPage();
        //echo $html;
        //*
        if ($html)
            $html = 1;
        else
            $pdf->writeHTML('<h1>No Data Found</h1>', true, false, true, false, '');
        //*/
        // set color for background
        $pdf->SetFillColor(255, 255, 215);

        // set font
        $pdf->SetFont('helvetica', '', 8);


        // reset pointer to the last page
        $pdf->lastPage();

        $rname = 'cc-jobreport-' . date('m-j-Y-g-i-a') . '.pdf';
        // ---------------------------------------------------------
        // echo $html;
        //Close and output PDF document
        $pdf->Output($rname, 'I');

        //============================================================+
        // END OF FILE
        //============================================================+
    }

    public function actionNewEarnedRevenueReport()
    {

        $model = new EarnedRevenueReportForm();
        if (isset($_POST['EarnedRevenueReportForm']))
        {
            $this->layout = '//layouts/space';
            $model->attributes = $_POST['EarnedRevenueReportForm'];
            $model->makeReportData();
            $this->render('newEarnedRevenueReport', array(
                'model' => $model,
            ));
        }
        else
        {
            $this->render('newEarnedRevenueReportForm', array(
                'model' => $model,
            ));
        }
    }
    public function actionDispatch($dispatch, $mail = false)
    {
        $dispatch = Dispatchdetails::model()->findByPk($dispatch);

        $customer = Customers::model()->findByPk($dispatch->custno);
        $location = Locations::model()->find('custno=:custno and locno=:locno',array(
            'custno'=>$dispatch->custno,
            'locno'=>$dispatch->locno
        ));
        $pdf = new DispatchPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('QSI');
        $pdf->SetTitle('Dispatch #' . $dispatch->dispatch);
        $pdf->SetSubject('PO');
        $pdf->SetKeywords('');

        $pdf->setMyHeaderData(  $dispatch->dispatch, $dispatch->receiveddate, $dispatch->custno);
        $pdf->setInvoiceType('PO');

        $pdf->setPrintHeader(true);
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        //$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 60, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 10);

        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        //set some language-dependent strings
        // $pdf->setLanguageArray($l);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('', '', 8);


        $pdf->AddPage();

        $receivedby = explode('@',$dispatch->receivedby);
        $html = '
        <table  style="width: 925px;"  cellspacing="0"  cellpadding="2" >

            <tr  >
            <td align="right" style="width: 100px;">
           <b> CUST NO:  </b> <br/>
            <b> LOCATION:</b> <br/>
            </td>

                <td align="left" style="width: 225px;">
                   ' . $location->custno . ' <br> &nbsp;'
            . $location->locno . ' <br/>
                  &nbsp;   ' . $customer->lastname . '<br/>
                    &nbsp;   ' . $location->locname . '<br>
                        ' . $location->add1 . '<br>
                   ' . $location->city.' ,' .$location->state .' '.$location->zip . '
                </td>

                <td  align="left" style="width: 100px;" >
             <b>Called in By</b> : <br/>
             &nbsp;&nbsp;<b>Department</b> :<br/>
             &nbsp;&nbsp;<b>Priority </b>:<br/>
             &nbsp;&nbsp;<b>Received By</b>:<br/>
             &nbsp;&nbsp;<b>Date Received</b>: <br/>
             &nbsp;&nbsp;<b>Time Received</b> : <br/>
             &nbsp;&nbsp;<b>P/O Number: </b><br/>
             &nbsp;&nbsp;<b>W/O Number:</b> <br/>
                </td align="left" >
                    <td  align="left"   >
                  &nbsp;'.$dispatch->calledinby.' <br/>
                 &nbsp;&nbsp;&nbsp;'.$dispatch->department.'<br/>
             &nbsp;&nbsp;&nbsp;'.$dispatch->priority.'<br/>
          &nbsp;&nbsp;&nbsp;'.$receivedby['0'].'<br/>
            &nbsp;&nbsp;&nbsp;'.$dispatch->receiveddate.'<br/>
      &nbsp;&nbsp;&nbsp;'.$dispatch->receivedtime.'<br/>
         &nbsp;&nbsp;&nbsp;'.$dispatch->ponumber.'<br/>
         &nbsp;&nbsp;&nbsp;'.$dispatch->wonumber.' <br/>
                    </td>

            </tr>
            </table>  ';
        //$html .= '<br/><h3> &nbsp;NOTES</h3>'.CHtml::tag('pre',array(),trim(strip_tags($dispatch->notes)));

        $rows = '';
        $crit = new CDbCriteria();
        $crit->condition = 'dispatch=:dispatch';
        $crit->params = array(
            'dispatch' => $dispatch->dispatch
        );
        $logList = DispatchTech::model()->findAll($crit);
        foreach ($logList as $item){
            if($item->empno == Null){
                $empnoText =  '0000 - Unassigned';
            } else {
                $empnoText = $item->employee->firstname . ' ' . $item->employee->lastname;
            }
            $starttime = convertDateToUS($item->startdate).'@'.convertDate('h:i A', $item->starttime);
            if(isset($item->enddate))
                $endtime = convertDateToUS($item->enddate).'@'.convertDate('h:i A', $item->endtime);
            else $endtime = '';
            $rows.="
                    <tr>
                        <td>$empnoText</td>
                        <td>$starttime  </td>
                        <td>$endtime   </td>
                        <td> {$item->status}</td>
                        <td> {$item->switchToStatus}</td>
                    </tr>

                ";
        }
        $html.='
            &nbsp;<br/> <h3 style="text-align: center;"> &nbsp;TECH LOG </h3>
            <table  cellspacing="0" cellpadding="3" >
            <tr>
                <th align="left" style="width:25%;border-bottom-style: solid;" ><b>Engineer</b></th>
                <th align="left" style="width:25%;border-bottom-style: solid;" ><b>Start</b></th>
                <th align="left" style="width:25%;border-bottom-style: solid;" ><b>End</b></th>
                <th align="left" style="width:15%;border-bottom-style: solid;" ><b>Active Status</b></th>
                <th align="left" style="width:10%;border-bottom-style: solid;" ><b>Switch to Status</b></th>
            </tr>
                        ' . $rows . '
            </table>';

        $rows='';

        $crit = new CDbCriteria();
        $crit->condition = 'dispatch=:dispatch';
        $crit->params = array(
            'dispatch' => $dispatch->dispatch
        );
        $logList = Dispatchequipment::model()->findAll($crit);
        foreach ($logList as $item){
            $equipmenttext = $item->getEquipmentName();

            $rows.="
                    <tr>

                        <td> {$item->id}</td>
                         <td>$equipmenttext</td>
                        <td> {$item->equipmentid}</td>
                         <td> {$item->notes}</td>
                    </tr>

                ";
        }
        if(!$rows) $rows = '<h6><b>N/A</b></h6>';
        $html.='<br/>
           &nbsp; <hr/> <h3 style="text-align: center;">&nbsp;EQUIPMENT LOG </h3>
            <table  cellspacing="0" cellpadding="3" >
<tr>
<th align="left" style="width:15%;border-bottom-style: solid;"><b>ID</b></th>
<th align="center" style="width:70%;border-bottom-style: solid;" ><b>Description</b></th>
<th align="right" style="width:15%;border-bottom-style: solid;" ><b>Serial</b></th>


</tr>
            ' . $rows . '
</table>';
        $rows = '';
        $crit = new CDbCriteria();
        $crit->condition = "dispatch=:dispatch and empno IS NULL AND custno !=''";
        $crit->params = array(
            'dispatch' => $dispatch->dispatch
        );
        $notesList = Notes::model()->findAll($crit);
        foreach ($notesList as $note){
            $rows.="
                <tr>
                <td>{$note->dateofnote} @ {$note->time} </td>
                <td>{$note->name}  </td>
                <td>{$note->note}   </td>

                </tr>

                ";
        }
        if(!$rows) $rows = '<h6><b>N/A</b></h6> ';
        $html.='
        <br/>
          &nbsp;   <hr/> <h3 style="text-align: center;"> &nbsp;CUSTOMER NOTES </h3>
            <table  cellspacing="0" cellpadding="3" >
<tr>
<th align="left" style="width:30%;border-bottom-style: solid;"><b>Date</b></th>
<th align="left" style="width:20%;border-bottom-style: solid;" ><b>Name</b></th>
<th align="left" style="width:50%;border-bottom-style: solid;" ><b>Note</b></th>

</tr>
            ' . $rows . '
</table>';
        $rows = '';
        $crit = new CDbCriteria();
        $crit->condition = "dispatch=:dispatch and custno IS NULL and private IS NULL or private !=1";
        $crit->params = array(
            'dispatch' => $dispatch->dispatch
        );
        $notesList = Notes::model()->findAll($crit);
        foreach ($notesList as $note){
            $name = Employees::getEmployeeName($note->empno);
            $rows.="
                <tr>
                <td>{$note->dateofnote} @ {$note->time} </td>
                <td>  $name    </td>
                <td> {$note->note}  </td>
                </tr>

                ";
        }
        if(!$rows) $rows = '<h4><b>N/A</b></h4>';
        $html.='
             &nbsp;       <hr/> <h3 style="text-align: center;">&nbsp;TECH NOTES </h3>
                    <table  cellspacing="0" cellpadding="3" >
        <tr>
        <th align="left" style="width:30%;border-bottom-style: solid;"><b>Date</b></th>
        <th align="left" style="width:20%;border-bottom-style: solid;" ><b>Name</b></th>
        <th align="left" style="width:50%;border-bottom-style: solid;" ><b>Note</b></th>

        </tr>
                    ' . $rows . '
        </table>';
        $rows = '';
        $crit = new CDbCriteria();
        $crit->condition = "dispatch=:dispatch";
        $crit->params = array(
            'dispatch' => $dispatch->dispatch
        );
        $partsList = Dispatchparts::model()->findAll($crit);
        foreach ($partsList as $item){
            if($item->employee!=null)
            {
                $name = $item->employee->firstname.' '.$item->employee->lastname;
            }
            $rows.="
                <tr>
                <td>{$item->warehouse} </td>
                <td>{$item->partno}  </td>
                <td>{$item->partdesc}  </td>
                <td>{$item->quanity}  </td>
                <td>  $name    </td>
                 <td>{$item->added_date}  </td>
                </tr>

                ";
        }
        if(!$rows) $rows = '<h4><b>N/A</b></h4>';
        $html.='
               &nbsp;  <br/    <hr/> <h3 style="text-align: center;"> &nbsp;PARTS LOG</h3>
                    <table  cellspacing="0" cellpadding="3" >
        <tr>
        <th align="left" style="width:15%;border-bottom-style: solid;"><b>Ware House</b></th>
        <th align="left" style="width:15%;border-bottom-style: solid;" ><b>Part NO</b></th>
        <th align="left" style="width:25%;border-bottom-style: solid;" ><b>Description</b></th>
        <th align="left" style="width:10%;border-bottom-style: solid;" ><b>QTY</b></th>
        <th align="left" style="width:20%;border-bottom-style: solid;" ><b>Added By</b></th>
        <th align="left" style="width:15%;border-bottom-style: solid;" ><b>Date</b></th>
        </tr>
                    ' . $rows . '
        </table><br/><br/><br/><br/><br/><br/>';

        $html.= '<table><tr><td></td></tr></table><br/><h3> &nbsp;SIGNATURES</h3><hr/>';
        $crit = new CDbCriteria();
        $crit->compare('dispatch',$dispatch->dispatch);
        $signaturesList = DispatchSignatures::model()->findAll($crit);
        foreach($signaturesList as $singnature){
            $html.= CHtml::image($singnature->filename,'',array("width"=>"400px")).'<br/>';
        }

        $pdf->writeHTML($html, true, false, true, false, '');


        // set color for background
        $pdf->SetFillColor(255, 255, 215);

        // set font
        $pdf->SetFont('helvetica', '', 8);


        // reset pointer to the last page
        $pdf->lastPage();

        if ($mail)
        {
            $body = $_POST['message'];
            $address = $_POST['email'];
            $emailArray = explode(',', $address);
            $subject = $_POST['subject'];
            $pdf->Output('pdf/dispatch-' . $dispatch->dispatch . '.pdf', 'F');
            $attachment = 'pdf/dispatch-' .$dispatch->dispatch . '.pdf';
            if (! EmailUtil::sendEmail($subject,$emailArray,$body,$attachment))
            {

                $result = array('success' => false, 'msg' => $mail->ErrorInfo);
                echo json_encode($result);
            }
            else
            {
                $log = new PrintLog();
                $log->date = date('Y-m-j');
                $log->time = date('h-i-s');
                $log->type = 'Dispatch';
                $log->number = $dispatch->dispatch;
                $log->emailto = $_POST['email'];
                $log->print = 'Yes';
                $log->save();
                $result = array('success' => true, 'msg' => 'Message sent!');
                echo json_encode($result);
            }
        }
        else
        {
            //Close and output PDF document
            $pdf->Output('dispatch-' . $dispatch->dispatch, 'I');
            $log = new PrintLog();
            $log->date = date('Y-m-j');
            $log->time = date('h-i-s');
            $log->type = 'Dispatch';
            $log->number = $dispatch->dispatch;
            $log->emailto = '';
            $log->print = 'Yes';
            $log->save();
        }

        // ---------------------------------------------------------
        //============================================================+
        // END OF FILE
        //============================================================+
    }
}

    
